<?php

namespace common\entities\official;

use Yii;
use common\support\OSS;

class MediaEntity extends \common\entities\ConfigEntity {

    public $resourcesFile;

    public static function tableName() {
        return 'myscrm_official_media';
    }

    public function rules() {
        return [
            [['dir_id'], 'required'],
            [['dir_id', 'size', 'created_time', 'modified_time', 'status'], 'integer'],
            [['name', 'type', 'image_info'], 'string', 'max' => 30],
            [['file'], 'string', 'max' => 255],
            [['resourcesFile'], 'file'],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => '编号',
            'dir_id' => '目录',
            'name' => '说明',
            'file' => '资源地址',
            'size' => '大小',
            'type' => '类型',
            'image_info' => '尺寸',
            'status' => '状态',
            'created_time' => '创建时间',
            'modified_time' => '修改时间',
        ];
    }

    public function getDir() {
        return $this->hasOne(DirEntity::className(), ['id' => 'dir_id']);
    }

    public function saveResourcesFile() {
        $file = $this->resourcesFile;
        $key = 'cmsmedia/' . date("Ym") . "/" . date("YmdH") . "/file_" . \common\support\StringHelper::uuid() . "." . $file->getExtension();
        OSS::upload($key, $file->tempName);
        $url = OSS::getUrl($key);
        if ($url) {
            $this->file = $url;
            $this->size = $file->size;
            $this->file = $file->extension;
            $this->update();
        }
        return true;
    }

    public function afterSaveBak($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        if ($this->resourcesFile instanceof \yii\web\UploadedFile) {
            $this->saveResourcesFile();
        }
        return true;
    }

    public function fileFmt() {
        $rs = '';
        if ($this->file) {
            if (in_array($this->type, array('jpg', 'gif', 'png', 'jpeg'))) {
                $rs = \yii\helpers\Html::img($this->file, ['height' => '40px']);
            } else {
                $rs = $this->file;
            }
        }
        return $rs;
    }

}
